package top.yongyan0624.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yongyan0624.entity.AlipayGroup;
import top.yongyan0624.entity.GoodsGroup;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Yongyan
 * @description: TODO
 * @date 2021/9/11
 **/
@RestController
@RequestMapping("/order")
public class AlipayGroupController extends BaseController {
    @PostMapping("/alipayGroup")
    @Transactional
    public String alipayGroup(@RequestBody AlipayGroup alipayGroup) throws AlipayApiException {
        //修改商品状态
        Map<Long, Integer> goodsMap = alipayGroup.getGoodsMap();
        List<GoodsGroup> goodsList = goodsGroupService.listByIds(goodsMap.keySet());
        goodsList.forEach(goods -> {
            if (goods.getAmount() <= 0) {
                throw new RuntimeException("商品:" + goods.getTitle() + "数量不足");
            }
            goods.setAmount(goods.getAmount() - goodsMap.get(goods.getId()));

        });
        goodsGroupService.updateBatchById(goodsList);

        //设置订单号
        alipayGroup.setOut_trade_no(UUID.randomUUID().toString());

        //设置订单名称
        String subject = StringUtils.join(
                goodsList
                        .stream()
                        .map(goods -> "[" + goods.getTitle() + "]*" + goodsMap.get(goods.getId()))
                        .collect(Collectors.toList()), ",");
        alipayGroup.setSubject(subject);

        //设置付款金额
        double amount = goodsList
                .stream()
                .mapToDouble(value -> value.getPrice() * goodsMap.get(value.getId()))
                .sum();
        alipayGroup.setTotal_amount(new DecimalFormat("#.00").format(amount));

        //设置商品描述
        alipayGroup.setBody(subject + "已售出，总价：" + amount);

        //设置goodsIds
        String goodsIds = StrUtil.join(",", alipayGroup.getGoodsMap().keySet());
        alipayGroup.setGoodsIds(goodsIds);

        //订单持久化
        alipayGroupService.save(alipayGroup);

        return alipayGroupService.aliPay(alipayGroup);
    }

}
